<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-button type="primary" @click="updatauserisblock = true"
        >添加角色</el-button
      >
      <el-table :data="roleslist" stripe style="width: 100%" border>
        <el-table-column type="expand">
          <template v-slot="scope">
            <el-row
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
              :class="['rowbt', i1 === 0 ? 'rowtop' : '']"
              class="centerrow"
            >
              <el-col :span="5">
                <el-tag closable @close="removetagbyid(scope.row, item1.id)">{{
                  item1.authName
                }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                  :class="[i2 === 0 ? '' : 'rowtop']"
                >
                  <el-col :span="5">
                    <el-tag
                      type="success"
                      closable
                      @close="removetagbyid(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i
                  ></el-col>
                  <el-col :span="19" class="centerrow">
                    <el-tag
                      type="warning"
                      @close="removetagbyid(scope.row, item3.id)"
                      closable
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      >{{ item3.authName }}</el-tag
                    ></el-col
                  >
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#" width="220"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色名称" width="320">
        </el-table-column>
        <el-table-column prop="roleName" label="角色描述" width="320">
        </el-table-column>
        <el-table-column label="操作" width="420">
          <template v-slot="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="reviseuser(scope.row.id)"
            >
              编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteusers(scope.row.id)"
              >删除</el-button
            >
            <el-button
              type="warning"
              icon="el-icon-share"
              size="mini"
              @click="showsetroles(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-dialog
        title="添加用户"
        :visible.sync="updatauserisblock"
        @close="updatarules"
      >
        <el-form :model="updataform" :rules="updataformrules" ref="updatafrom">
          <el-form-item label="角色名称" prop="roleName">
            <el-input
              v-model="updataform.roleName"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input
              v-model="updataform.roleDesc"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="updatauserisblock = false">取 消</el-button>
          <el-button type="primary" @click="updatauser">确 定</el-button>
        </div>
      </el-dialog>
      <el-dialog
        title="修改信息"
        :visible.sync="newlistblock"
        @close="reviseuserrules"
      >
        <el-form :model="reviselist" :rules="reviselistrules" ref="reviselist">
          <el-form-item label="角色名称" prop="roleName">
            <el-input
              v-model="reviselist.roleName"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input
              v-model="reviselist.roleDesc"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="newlistblock = false">取 消</el-button>
          <el-button type="primary" @click="submitnewlist">确 定</el-button>
        </div>
      </el-dialog>
      <el-dialog title="删除" :visible.sync="deleteuser">
        <h4>是否删除该用户</h4>
        <span slot="footer" class="dialog-footer">
          <el-button @click="deleteuser = false">取 消</el-button>
          <el-button type="primary" @click="removeuser">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
    <el-dialog
      title="分配权限"
      :visible.sync="showsetisroles"
      width="50%"
      @close="closeclearkeys"
    >
      <el-tree
        :data="showsetisrolesinfo"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defkeys"
        ref='treeref'
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showsetisroles = false">取 消</el-button>
        <el-button type="primary" @click="allrights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      roleslist: [],
      updatauserisblock: false,
      updataform: {
        roleName: "",
        roleDesc: "",
      },
      updataformrules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
        ],
      },
      reviselist: {},
      reviselistrules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
        ],
      },
      newlistblock: false,
      deleteuser: false,
      removeid: "",
      showsetisroles: false,
      showsetisrolesinfo: [],
      treeProps: {
        label: "authName",
        children: "children",
      },
      defkeys: [],
      rolesid:''
    };
  },
  created() {
    this.getroleslist();
  },
  methods: {
    async getroleslist() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) return this.$message.error("获取信息失败");
      this.$message.success("获取信息成功");
      this.roleslist = res.data;
    },
    updatarules() {
      this.$refs.updatafrom.resetFields();
    },
    updatauser() {
      this.$refs.updatafrom.validate(async (valid) => {
        if (!valid) return this.$message.error("检查数据合法性");
        const { data: res } = await this.$http.post("roles", {
          roleName: this.updataform.roleName,
          roleDesc: this.updataform.roleDesc,
        });
        if (res.meta.status !== 201) {
          return this.$message.error("更新失败");
        }
        this.getroleslist();
        return this.$message.success("更新成功");
      });
      this.updatauserisblock = !this.updatauserisblock;
    },
    reviseuserrules() {
      this.$refs.reviselist.resetFields();
    },
    async reviseuser(id) {
      const { data: res } = await this.$http.get(`roles/${id}`);
      if (res.meta.status !== 200) {
        return this.$message.error("获取信息失败");
      }
      this.reviselist = res.data;
      this.newlistblock = true;
    },
    submitnewlist() {
      console.log(this.reviselist);
      this.$refs.reviselist.validate(async (valid) => {
        if (!valid) return this.$message.error("检查数据合法性");
        const { data: res } = await this.$http.put(
          `roles/${this.reviselist.roleId}`,
          {
            roleName: this.reviselist.roleName,
            roleDesc: this.reviselist.roleDesc,
          }
        );
        if (res.meta.status !== 200) {
          return this.$message.error("更新失败");
        }
        this.getroleslist();
        return this.$message.success("更新成功");
      });
      this.newlistblock = !this.newlistblock;
    },
    deleteusers(id) {
      this.removeid = id;
      this.deleteuser = true;
    },
    async removeuser() {
      const { data: res } = await this.$http.delete(`roles/${this.removeid}`);
      if (res.meta.status !== 200) {
        return this.$message.error("删除失败");
      }
      this.$message.success("删除成功");
      this.getroleslist();
      this.deleteuser = false;
    },
    async removetagbyid(role, rightsid) {
      const rightrule = await this.$confirm("将永久删除该权限", "删除权限", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).catch((err) => err);
      console.log(rightrule);
      if (rightrule !== "confirm") return this.$message.info("取消删除");
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightsid}`
      );
      if (res.meta.status !== 200) return this.$message.error("删除失败");
      role.children = res.data;
      console.log(res);
    },
    async showsetroles(roles) {
      this.rolesid = roles.id
      const res = await this.$http.get("rights/tree");
      if (res.status !== 200) return this.$message.error("获取权限列表失败");
      this.showsetisrolesinfo = res.data.data;
      this.getshowkeys(roles, this.defkeys);
      this.showsetisroles = true;
    },
    getshowkeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach((item) => {
        this.getshowkeys(item, arr);
      });
    },
    closeclearkeys() {
      this.defkeys = [];
    },
    async allrights(){
      const allkeys = [...this.$refs.treeref.getCheckedKeys(),...this.$refs.treeref.getHalfCheckedKeys()]
      const keys = allkeys.join(',')
      const {data:res} = await this.$http.post(`roles/${this.rolesid}/rights`,{rids:keys})
      if(res.meta.status!==200) return this.$message.error('更新失败')
      this.getroleslist()
    this.$message.success('更新成功')
       this.showsetisroles=false
    }
  },
};
</script>

<style scoped>
.el-card {
  margin-top: 20px;
  margin-left: 20px;
}
.el-table {
  margin-top: 20px;
}
.el-row {
  margin-left: 20px;
}
.el-tag {
  margin: 7px;
}
.rowtop {
  border-top: 1px solid gray;
}
.rowbt {
  border-bottom: 1px solid gray;
}
.centerrow {
  display: flex;
  align-items: center;
}
</style>
